package simon.tuke

import androidx.lifecycle.MutableLiveData
import java.io.Serializable
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

fun <V : Serializable?> value(
    def: V? = null,
    key: String,
    isCache: Boolean = false
) = object : ReadWriteProperty<Any?, V?> {

    @Volatile
    private var mValue: V? = null
        set(value) {
            Tuke.write(key, value, isCache)
            field = value
        }
        get() {
            return field ?: Tuke[key, def, isCache]
        }

    override fun getValue(thisRef: Any?, property: KProperty<*>): V? {
        return mValue
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: V?) {
        mValue = value
    }
}

fun <V : Serializable?> livedata(
    def: V? = null,
    key: String,
    isCache: Boolean = false
) = object : ReadOnlyProperty<Any?, MutableLiveData<V>> {

    private val mLiveData = MutableLiveData<V>(Tuke[key, def, isCache])

    init {
        mLiveData.observeForever {
            Tuke.write(key, it, isCache)
        }
    }

    override fun getValue(thisRef: Any?, property: KProperty<*>): MutableLiveData<V> {
        return mLiveData
    }
}